$NG.AllReady(function (page, { useUpdateRow, useBeforeClick, useValuesChange, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_pc_liquid_m");
    const grid = $NG.getCmpApi("p_form_pc_liquid_d");
    const grid2 = $NG.getCmpApi("p_form_pc_liquid_d2");
    const grid3 = $NG.getCmpApi("p_form_pc_liquid_d3");
    const grid4 = $NG.getCmpApi("p_form_pc_liquid_d4");
    const grid5 = $NG.getCmpApi("p_form_pc_liquid_d5");
    // const grid = $NG.getCmpApi("p_form_pc_liquid_d");
    if (page.oType == "add") {
        filterCntMain()
        getPtInfoByPhid()
        getCntMInfoByPhid()
        getFbsInPay()
        getGysInPayInfo()
        getPdwlTotalInfo()
        getXshtTotalInfo()
        getCgrkTotalAmt()
        getCbjyjlTotalAmt()
        getSrbyInfoByPhidPc()
        getSsxmJlTotalAmt()
        getGcsjTotalAmt()
        getSbqdHeadInfoByPhidPc()
        getSbqdTotalGapAmt()
        getSjcztbTotalAmt()
        getSywzFxInfo()
        getSbqdInitFromInfo()
        getFbjsTotalAmtWs()
        getCntCount("p_form_pc_liquid_m", "u_cnt_name", mainCnt)
        var pc = mstform.getItem("phid_pc");
        console.log(pc.getValue());
        console.log("123123");
        if (pc.getValue() > "0") {
            getQSInfo(pc.getValue())

            var pcname = mstform.getItem("phid_pc").getRawValue().label
            $NG.updateState((updater) => {
                //文本
                updater.data.p_form_pc_liquid_m.setProps({
                    bill_name: pcname + "项目清算",
                });
            });
        }
    }
    function getHeadVal(str) {
        return mstform.getItem(str).getValue()
    }
    const sumAmtHead = (map, exc) => {
        const date = new Date()
        map.u_sr_add_dec = map.u_app_amt - map.u_srqrje
        map.u_cnt_wcl = (Number(map.u_app_amt) || 0) ? (Number(map.u_app_amt) || 0) / (Number(map.u_ht_amt_ori) || 0) : 0
        map.u_mjllzj = map.u_qsmll - map.u_srmll
        map.u_qkyje = map.u_mjllzj * map.u_app_amt
        map.bill_name = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}${mstform.getItem("phid_fill_psn").getText()}${mstform.getItem("phid_pc").getText()}项目清算`

    }
    // 监听项目部分字段
    // 表头赋值/计算(封装)
    $NG.setHeadValue = {}
    initHead('p_form_pc_liquid_m', sumAmtHead)
    function initHead(table, fun) {
        const mstform = $NG.getCmpApi(table);
        const val = mstform.getValues()
        const headKey = ["bill_name", "u_ht_amt_ori", "u_qdmll", "u_qzbg_amt", "u_htxe", "u_dqmll", "u_cgcb", "u_fbcb",
            "u_ssjl", "u_cbjyjl", "u_cz_byje", "u_srqrje", "u_app_amt", "u_sr_add_dec", "u_cnt_wcl",
            "u_qsmll", "u_srmll", "u_mjllzj", "u_qkyje", "u_sywzjr"]

        // 临时变量记录，不参与赋值(当缓存使用)可以参与表头计算
        const excludes = []

        // 劫持原表头赋值函数，防止2边数据不同步
        const option = $NG.updateState;
        $NG.updateState = function (...args) {
            const updater = args[0];
            args[0] = function (...innerArgs) {
                const targetObj = innerArgs[0].data[table];
                if (targetObj) {
                    const originalSetProps = targetObj.setProps;
                    targetObj.setProps = function (props) {
                        if (!props.hook) {
                            for (let key in props) {
                                if (headKey.includes(key)) {
                                    $NG.setHeadValue.manualSet(key, props[key]);
                                }
                            }
                        }
                        return originalSetProps.call(this, props);
                    };
                }
                return updater.apply(this, innerArgs);
            };

            option.apply(this, args);
        };

        Object.defineProperties($NG.setHeadValue, {
            _sumAmt: { // 赋值渲染 + 表头计算计算
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key) { // 要跳过的key
                    const map = headKey.reduce((value, item) => {
                        value[item] = this["_" + item]
                        return value
                    }, {})
                    // 排除
                    const exclude = excludes.reduce((value, item) => {
                        value[item] = this["_" + item]
                        return value
                    }, {})
                    // 表头计算
                    fun(map, exclude)

                    if (key) {
                        delete map[key]
                    }
                    console.log(`赋值信息`, map, key);
                    $NG.updateState((updater) => {
                        updater.data[table].setProps({
                            hook: true,
                            ...map
                        })
                    })
                }
            },
            noRender: { // 不进行渲染赋值
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key, val) {
                    this["_" + key] = val
                }
            },
            manualSet: { // 禁止渲染手输入 但要计算
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (key, val) {
                    this["_" + key] = val
                    this._sumAmt(key)
                }
            },
            manySetVal: { // 多字段赋值，类 _sunAmt
                writable: false,
                enumerable: true,
                configurable: false,
                value: function (map) {
                    for (let key in map) {
                        this['_' + key] = map[key]
                    }
                    this._sumAmt()
                }
            }
        })
        // 创建不可枚举字段，让不加 _ 的变量代理私有属性(防异步)
        const ini = (item, bool) => {
            Object.defineProperties($NG.setHeadValue, {
                [item]: {
                    enumerable: true,
                    configurable: false,
                    set(val) {
                        this['_' + item] = val
                        if (window._sum_amt_lock) {
                            clearTimeout(window._sum_amt_lock)
                        }
                        window._sum_amt_lock = setTimeout(() => {
                            this._sumAmt()
                        }, 1000)
                    },
                    get() {
                        return this['_' + item]
                    }
                },
            })
            Object.defineProperties($NG.setHeadValue, {
                ["_" + item]: {
                    value: val[item],// 设置初始值
                    writable: true,
                    enumerable: false,
                    configurable: false,
                },
            })
            // 如果发生手输入改变
            if (bool) {
                useValuesChange(({ args }) => {
                    $NG.setHeadValue.manualSet(item, args[0][item])
                }, item)
            }
        }
        headKey.forEach(item => {
            ini(item, true)
        })
        excludes.forEach(el => {
            ini(el, false)
        })
    }



    useBeforeClick(async function ({ args }) {
        //按钮点击前事件
        $NG.execServer("getRkYhInfo", { pc: mstform.getItem("phid_pc").getValue() }, function (res) {
            console.log(res);
            const data = JSON.parse(res.data);
            const ce = data[0].extendObjects.ce;
            if (ce) {
                $NG.alert("存在要货单的物资未入库，全部入库后方可进行项目清算")
                return false;
            } else {

            }
        });
        // return false; // 取消向下执行
    }, "save");

    //项目名称变化时自动带入产品线、事业部等
    useValuesChange(({ args }) => {

        console.log(args[0]);
        //const phid_pc = args[0].pc.PhId;
        const phid_pc = args[0].phid_pc.value;
        console.log(phid_pc);
        //从项目取值
        if (phid_pc) {
            console.log(phid_pc);
            const mstform = $NG.getCmpApi("p_form_pc_liquid_m");
            getQSInfo(phid_pc)

            var pcname = mstform.getItem("phid_pc").getRawValue().label
            $NG.updateState((updater) => {
                //文本
                updater.data.p_form_pc_liquid_m.setProps({
                    bill_name: pcname + "项目清算",
                });
            });
        }
        getCntCount("p_form_pc_liquid_m", "u_cnt_name", mainCnt)
        getPtInfoByPhid()
        getCbjyjlTotalAmt()
        getSsxmJlTotalAmt()
        getCgrkTotalAmt()
        getSrbyInfoByPhidPc()
        filterCntMain()
        getSbqdHeadInfoByPhidPc()
        getGcsjTotalAmt()
        getFbsInPay()
        getGysInPayInfo()
        getFbsInPay()
        getGysInPayInfo()
        getPdwlTotalInfo()
        getXshtTotalInfo()
        getSbqdTotalGapAmt()
        getSjcztbTotalAmt()
        getSywzFxInfo()
        getSbqdInitFromInfo()
        getFbjsTotalAmtWs()
    }, "p_form_pc_liquid_m.phid_pc");

    function mainCnt() {
        getCntMInfoByPhid()

    }

    useValuesChange(({ args }) => {
        mainCnt()
    }, "p_form_pc_liquid_m.u_cnt_name");

    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_pc_liquid_d");

    useUpdateRows(({ args }) => {
        const rows = args[0]
        rows.forEach(item => {
            item.u_kpwsn = ((Number(item.u_ykphs) || 0) / (1 + 0.09)).toFixed(2),
                item.u_kpwssix = ((Number(item.u_kphssix) || 0) / (1 + 0.06)).toFixed(2),
                item.u_kpwsth = ((Number(item.u_kphsth) || 0) / (1 + 0.03)).toFixed(2),
                item.u_kpwsone = ((Number(item.u_kphsone) || 0) / (1 + 0.01)).toFixed(2),
                item.u_kpwsthy = ((Number(item.u_kphsthy) || 0) / (1 + 0.13)).toFixed(2),
                item.u_kpwsxj = (Number(item.u_kpwsn) || 0) + (Number(item.u_kpwssix) || 0) + (Number(item.u_kpwsth) || 0) +
                (Number(item.u_kpwsone) || 0) + (Number(item.u_kpwsthy) || 0) + (Number(item.u_kpwsthy) || 0)
        })

        grid2.refreshView()
    }, "p_form_pc_liquid_d2")
    useUpdateRows(({ args }) => {

    }, "p_form_pc_liquid_d3")
    useUpdateRows(({ args }) => {
        const rows = args[0]
        rows.forEach(item => {
            item.u_jypdcy = item.u_jysl - item.u_pdsl
            item.u_dhslcy = item.u_dhsl - item.u_slsl
        })
        grid4.refreshView()
    }, "p_form_pc_liquid_d4")
    useUpdateRows(({ args }) => {
        const rows = args[0]
        rows.forEach(item => {
            item.u_wkpsq = item.u_sdje - (Number(item.u_ykpsq) || 0)
            item.u_wkpsl = item.u_sdje - (Number(item.u_ykpsl) || 0)
            item.u_wkpss = item.u_sdje - (Number(item.u_ykpss) || 0)
            item.u_wkpj = item.u_sdje - (Number(item.u_ykpj) || 0)
            item.u_wkpl = item.u_sdje - (Number(item.u_ykpl) || 0)
            item.u_wkpli = item.u_sdje - (Number(item.u_ykpli) || 0)
            item.u_wkphj = item.u_wkpsq + item.u_wkpsl + item.u_wkpss + item.u_wkpj + item.u_wkpl + item.u_wkpli

            item.u_wqrsrsq = item.u_sdje - (Number(item.u_yqrsrsq) || 0)
            item.u_wqrsrsl = item.u_sdje - (Number(item.u_yqrsrsl) || 0)
            item.u_wqrsrss = item.u_sdje - (Number(item.u_yqrsrss) || 0)
            item.u_wqrsrj = item.u_sdje - (Number(item.u_yqrsrj) || 0)
            item.u_wqrsrl = item.u_sdje - (Number(item.u_yqrsrl) || 0)
            item.u_wqrsrli = item.u_sdje - (Number(item.u_yqrsrli) || 0)
            item.u_wqrsrhj = item.u_wqrsrsq + item.u_wqrsrsl + item.u_wqrsrss + item.u_wqrsrj + item.u_wqrsrl + item.u_wqrsrli
            item.u_srhj = item.u_sdje
        })
        grid5.refreshView()
    }, "p_form_pc_liquid_d5")
    function sumAmt() {
        const rows1 = grid.getRows()
        let czTotal = 0
        let mle_amt = 0
        let sr_amt = 0
        rows1.forEach((item, index) => {
            // 使用可选链操作符 (?.) 来安全地访问属性，并提供默认值 '0' 以防属性不存在或为非数字
            const amt = parseFloat(item.amt ?? '0');
            const u_sscb = parseFloat(item.u_sscb ?? '0');
            const u_fsscb = parseFloat(item.u_fsscb ?? '0');
            const u_qzbg = parseFloat(item.u_qzbg ?? '0');
            const u_yrzcb = parseFloat(item.u_yrzcb ?? '0');
            const u_hqcb = parseFloat(item.u_hqcb ?? '0');


            // 只有当所有需要的字段都存在并且是有效的数字时才进行计算
            if (!isNaN(amt) && !isNaN(u_sscb) && !isNaN(u_fsscb) && !isNaN(u_qzbg) && !isNaN(u_yrzcb) && !isNaN(u_hqcb)) {
                item.u_sjhj = amt + u_sscb + u_fsscb + u_qzbg;
                item.u_total = u_yrzcb + u_hqcb;
                item.u_jy = item.u_sjhj - item.u_total;
            }
            if (item.u_pc_no == '毛利额') {
                mle_amt = (Number(item.u_total) || 0)
            } else if (item.u_pc_no == '收入') {
                sr_amt = (Number(item.u_total) || 0)
            }
            czTotal += (Number(item.u_total) || 0)
        })
        // 筛选出毛利额 和 收入
        const datas = rows1.reduce((value, item) => {
            if (item.u_pc_no == '毛利额') {
                value[0] = item
            } else if (item.u_pc_no == '收入') {
                value[1] = item
            } else if (item.u_pc_no == '评审毛利率') {
                value[2] = item
            }
            return value
        }, [null, null, null])
        // 计算毛利
        const keys = ["amt", "u_sscb", "u_fsscb", "u_qzbg", "u_sjhj", "u_yrzcb", "u_hqcb", "u_total"]
        keys.forEach(item => {
            datas[2][item] = (Number(datas[0][item]) || 0) ? (Number(datas[0][item]) || 0) / (Number(datas[1][item]) || 0) : 0
        })
        console.log(`毛利比例`, mle_amt, sr_amt, (mle_amt / sr_amt));
        $NG.setHeadValue.u_qsmll = mle_amt ? (mle_amt / sr_amt) : 0
        // $NG.updateState((updater) => {
        //     updater.data.p_form_pc_liquid_m.setProps({
        //         u_cz_byje: czTotal
        //     })
        // })
        grid.refreshView()
    }

    //获取合同信息
    function getCntMInfoByPhid(params) {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_name").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log('获取合同信息', datas);
            $NG.updateState((updater) => {
                updater.data.p_form_pc_liquid_m.setProps({
                    u_cnt_no: datas.pcm_no, //合同编号
                    u_ht_amt_ori: datas.cnt_amt_init,
                    u_total_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同金额
                    u_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同金额
                    u_htxe: datas.cnt_sum_vat_fc, //合同价税合计
                    //产品线
                    user_product_line: {
                        value: datas.midwife_phid,
                        label: datas.midwife_name,
                    },
                    //合同类型
                    u_cnt_type: {
                        value: datas.pct_id,
                        label: datas.pct_name,
                    },
                    //甲方单位
                    u_customer: {
                        value: datas.customer_id,
                        label: datas.customer_name,
                    },
                    //乙方单位
                    supply: {
                        value: datas.supply_id,
                        label: datas.supply_name,
                    },
                    //发票类型
                    u_invoice_type: {
                        value: datas.invoice_type_phid,
                        label: datas.invoice_type_name,
                    },
                    //购方信息（客户信息）（收票单位信息）
                    //单位名称
                    tick_id: {
                        value: datas.tick_id,
                        label: datas.tick_name,
                    },
                    //单位编码
                    tick_no: datas.tick_no,
                    //社会信用代码
                    tick_unisocialcredit: datas.tick_unisocialcredit,
                    //单位地址
                    tick_taxaddress: datas.tick_taxaddress,
                    //联系电话
                    tick_taxtelephone: datas.tick_taxtelephone,
                    //银行名称
                    tick_taxbankid: {
                        value: datas.tick_taxbankid,
                        label: datas.tick_taxbankname,
                    },
                    //银行账号
                    tick_taxaccountno: datas.tick_taxaccountno,
                    //销方信息（供应商信息）（开票单位信息）
                    //单位名称
                    inv_id: { value: datas.inv_id, label: datas.inv_name },
                    //单位编码
                    inv_no: datas.inv_no,
                    //社会信用代码
                    inv_unisocialcredit: datas.inv_unisocialcredit,
                    //单位地址
                    inv_taxaddress: datas.inv_taxaddress,
                    //联系电话
                    inv_taxtelephone: datas.inv_taxtelephone,
                    //银行名称
                    inv_taxbankid: {
                        value: datas.inv_taxbankid,
                        label: datas.inv_taxbankname,
                    },
                    //银行账号
                    inv_taxaccountno: datas.inv_taxaccountno,
                });
            });
            // getQzInfo();
        });
    }
    //根据项目筛选合同
    function filterCntMain() {
        $NG.updateUI((updater, state) => {
            console.log("过滤参数检查", updater);
            updater.fieldSetForm.p_form_pc_liquid_m.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = mstform.getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!mstform.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1, //合同类型
                        phid_pc: mstform.getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }
    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`项目信息`, datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_pc_liquid_m.setProps({
                        u_pc_no: datas.pc_no, //项目编号
                        u_agreed_sts_dt: datas.start_date, //计划完工日期
                        u_agreed_pcl_dt: datas.end_date, //计划竣工日期
                        u_xmjl: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        u_sqgw: {
                            //售前顾问
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //大区
                        u_region: {
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        u_regional_center: {
                            //区域中心
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        u_product_line: {
                            //产品线
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        phid_org: {
                            value: datas.org_phid,
                            label: datas.org_name
                        },
                        u_pc_type: {
                            //项目类型
                            value: datas.type_phid,
                            label: datas.type_name,
                        },
                        u_jsnr: datas.descript
                    });
                });
            });
        }
    }
    // 获取采购入库的相关金额
    function getCgrkTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getCgrkTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_pc_liquid_m.setProps({
                    u_cgcb: (Number(_data.total_amt_ws) || 0)
                })
            })
        })
    }
    // 获取实施项目激励的费用合计
    function getSsxmJlTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSsxmJlTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_pc_liquid_m.setProps({
                    u_ssjl: (Number(_data.total_amt) || 0)
                })
            })
        })
    }

    // 获取成本结余激励费用
    function getCbjyjlTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getCbjyjlTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_pc_liquid_m.setProps({
                    u_cbjyjl: (Number(_data.total_amt) || 0)
                })
            })
        })

    }
    // 获取收入报验金额
    function getSrbyInfoByPhidPc() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSrbyInfoByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_srqrje = (Number(_data.total_amt) || 0)
            // $NG.updateState((updater)=>{
            //     updater.data.p_form_pc_liquid_m.setProps({
            //         u_cz_byje:(Number(_data.total_amt_vat) || 0)
            //     })
            // })
        })
    }

    // 获取实际产值填报
    function getSjcztbTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSjcztbTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_cz_byje = datas.total_amt
        })
    }

    // 获取设备清单表头信息
    function getSbqdHeadInfoByPhidPc() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSbqdHeadInfoByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects

            $NG.updateState((updater) => {
                updater.data.p_form_pc_liquid_m.setProps({
                    u_dqmll: (Number(_data.u_signed_gm_rate) || 0),
                })
            })
        })
    }

    // 获取设备清单初始单的数据
    function getSbqdInitFromInfo() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getSbqdInitFromInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_qdmll = datas.u_signed_gm_rate
        })
    }

    // 获取成本核算相关信息
    function getCbhsHeadInfo() {
        const phid_pc = getHeadVal("phid_pc")
        if (!phid_pc) return
        $NG.execServer("getCbhsHeadInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_yjsdmll = datas.u_ycztwgmll
        })
    }

    // 获取工程审计金额
    function getGcsjTotalAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getGcsjTotalAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_app_amt = (Number(_data.cb_total_amt) || 0)
            // $NG.updateState((updater)=>{
            //     updater.data.p_form_pc_liquid_m.setProps({
            //         u_app_amt:(Number(_data.total_amt) || 0)
            //     })
            // })
        })
    }

    // 获取设备清单变更签证变更金额
    function getSbqdTotalGapAmt() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSbqdTotalGapAmt", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_qzbg_amt = _data.eq_total_amt_vat
        })
    }

    // // 获取分包应付单本次申请金额汇总
    // function getFbyfdTotalAmtByPhidPc() {
    //     const phid_pc = mstform.getItem("phid_pc").getValue()
    //     if (!phid_pc) return
    //     $NG.execServer("getFbyfdTotalAmtByPhidPc", { phid_pc }, (res) => {
    //         if (res.count == 0) return
    //         const datas = JSON.parse(res.data)[0].extendObjects
    //         $NG.setHeadValue.u_fbcb = datas.hd_total_amt
    //     })
    // }
    // 获取分包结算金额
    function getFbjsTotalAmtWs() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getFbjsTotalAmtWs", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_fbcb = datas.total_amt
        })
    }

    // 剩余物资物资分析
    function getSywzFxInfo() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getSywzFxInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.setHeadValue.u_sywzjr = datas.total_amt
        })
    }
    // 根据项目获取分包商付款信息
    function getFbsInPay() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getFbsInPay", { phid_pc }, (res) => {
            const _data = JSON.parse(res.data).reduce((value, item) => {
                const el = item.extendObjects
                const va = value[el.cntphid]
                if (va) {
                    const temp = value[el.cntphid]
                    const temp_key = Object.keys(temp)
                    console.log(`debug --- temp`, temp);
                    if (temp_key.includes(el.fp_rate) && temp[el.fp_rate].u_fbdw == el.u_fbdw) {
                        temp[el.fp_rate].fp_amt_vat += (Number(el.fp_amt_vat) || 0)
                    }
                } else {
                    value[el.cntphid] = {}
                    value[el.cntphid][el.fp_rate] = el

                }
                return value
            }, {})
            window._catch_test1 = _data
            const rows = []
            for (let key in _data) {
                let _row = {}
                let k = null
                for (k in _data[key]) {
                    const element = _data[key][k]
                    let _key = ''
                    switch ((Number(k) || 0)) {
                        case 0.06:
                            _key = 'u_kphssix'
                            break
                        case 0.09:
                            _key = 'u_ykphs'
                            break
                        case 0.03:
                            _key = 'u_kphsth'
                            break
                        case 0.01:
                            _key = 'u_kphsone'
                            break
                        case 0.13:
                            _key = 'u_kphsthy'
                            break
                    }
                    console.log(`debug!%`, element);
                    // debugger
                    if (!_row[_key]) {
                        _row[_key] = (Number(element.fp_amt_vat) || 0)
                    } else {
                        _row[_key] += (Number(element.fp_amt_vat) || 0)
                    }
                    // debugger
                }

                //小计
                const amt_key = ["u_kphssix", "u_ykphs", "u_kphsth", "u_kphsone", "u_kphsthy"]
                _row.u_xj = amt_key.reduce((value, item) => {
                    value += (Number(_row[item]) || 0)
                    return value
                }, 0)
                let js_amt_vat = (Number(_data[key][k].fbjs_js_amt) || 0)
                let js_amt = (Number(_data[key][k].fbjs_js_amt_vat) || 0)
                if(!(Number(_data[key][k].fbjs_js_amt) || 0) && !(Number(_data[key][k].fbjs_js_amt_vat) || 0)){
                    js_amt_vat = (Number(_data[key][k].fbjs_gc_amt_vat) || 0)
                    js_amt = (Number(_data[key][k].fbjs_gc_amt) || 0)
                }
                _row = {
                    ..._row,
                    u_kpwsn: ((Number(_row.u_ykphs) || 0) / (1 + 0.09)).toFixed(2),
                    u_kpwssix :((Number(_row.u_kphssix) || 0) / (1 + 0.06)).toFixed(2),
                    u_kpwsth : ((Number(_row.u_kphsth) || 0) / (1 + 0.03)).toFixed(2),
                    u_kpwsone : ((Number(_row.u_kphsone) || 0) / (1 + 0.01)).toFixed(2),
                    u_kpwsthy : ((Number(_row.u_kphsthy) || 0) / (1 + 0.13)).toFixed(2),
                    u_kpwsxj : (Number(_row.u_kpwsn) || 0) + (Number(_row.u_kpwssix) || 0) + (Number(_row.u_kpwsth) || 0) +
                        (Number(_row.u_kpwsone) || 0) + (Number(_row.u_kpwsthy) || 0) + (Number(_row.u_kpwsthy) || 0),
                    u_fbxmh: _data[key][k].cnt_no,
                    u_fbdw: _data[key][k].fbdw_phid,
                    u_fbdw_EXName: _data[key][k].fbdw_name,
                    u_fbhshte: _data[key][k].cnt_amt_vat,
                    u_fbhtsl: _data[key][k].cnt_taxrate,
                    u_wkpje: js_amt_vat - (Number(_row.u_xj) || 0),
                    u_nssde: js_amt_vat,
                    u_nssdws: js_amt,
                    u_xjj: (Number(_row.u_kpwsxj) || 0) + (js_amt - (Number(_row.u_kpwsxj) || 0)) * (1 + _data[key][k].cnt_taxrate),
                    u_dkpws: (js_amt - (Number(_row.u_kpwsxj) || 0)) * (1 + _data[key][k].cnt_taxrate)
                }
                
                console.log(`分包准备添加的数据`, _row,js_amt,(js_amt - (Number(_row.u_kpwsxj) || 0)) * (1 + _data[key][k].cnt_taxrate));
                rows.push({ ..._row })
            }
            console.log(`分包商明细`, rows);
            grid2.clearRows().then(() => {
                grid2.addRows([...rows])
            })
        })
    }
    // 根据项目获取采购合同机器采购应付单的相关信息

    function getGysInPayInfo() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getGysInPayInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data).reduce((value, item) => {
                const el = item.extendObjects
                console.log(`debug测试`, (Number(el.bckp_amt) || 0) - (Number(el.zfd_total_amt) || 0));
                value.push({
                    u_cgdhh: el.cnt_no,
                    u_gys_EXName: el.jfdw_name,
                    u_gys: el.jfdw_phid,
                    u_cgddqd: el.cnt_amt_vat,
                    u_sjzxje: el.bqyf_amt_vat,
                    u_ykpje: el.bckp_amt,
                    u_yfkje: el.zfd_total_amt,
                    u_wkpje: (Number(el.bqyf_amt_vat) || 0) - (Number(el.bckp_amt) || 0),
                    u_wfkje: (Number(el.bckp_amt) || 0) - (Number(el.zfd_total_amt) || 0)
                })
                return value
            }, [])
            grid3.clearRows().then(() => {
                grid3.addRows([..._data])
            })
        })
    }
    // 根据项目获取采购入库分包领料盘点物料信息
    function getPdwlTotalInfo() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getPdwlTotalInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data).reduce((value, item) => {
                const el = item.extendObjects
                value.push({
                    u_wlbm: el.itemno,
                    u_wlmc: el.phid_itemdata,
                    u_wlmc_EXName: el.phid_itemname,
                    u_dhsl: el.dh_qty,
                    u_slsl: el.sl_qty,
                    u_cksl: el.ll_qty,
                    u_jysl: el.sy_qty,
                    u_pdsl: el.pd_qty,
                })
                return value
            }, [])
            grid4.clearRows().then(() => {
                grid4.addRows([..._data])
            })
        })
    }
    // 根据项目获取销售合同的相关信息汇总
    function getXshtTotalInfo() {
        const phid_pc = mstform.getItem("phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getXshtTotalInfo", { phid_pc }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data).reduce((value, item) => {
                const el = item.extendObjects
                const temp = value[el.cntphid]
                if (temp) {
                    if (temp[el.taxrate]) {
                        temp[el.taxrate] += (Number(el.kp_amt_vat) || 0)
                    }
                } else {
                    value[el.cntphid] = {}
                    value[el.cntphid]['item'] = el
                    value[el.cntphid][el.taxrate] = (Number(el.kp_amt_vat) || 0)
                }
                return value
            }, {})
            $NG.execServer("getSrbyTotalInfo", { phid_pc }, (res) => {
                let datas = []
                if (res.count != 0) {
                    datas = JSON.parse(res.data).reduce((value, item) => {
                        value.push(item.extendObjects)
                        return value
                    }, [])
                }

                window._catch_sybyData = _data
                const rows = []
                for (let key in window._catch_sybyData) {
                    const item = window._catch_sybyData[key]
                    const el = item.item
                    let by = datas.filter(it => {
                        if (it.u_cnt_name == el.cntphid) {
                            return it
                        }
                    })[0]
                    if (!by) {
                        by = {}
                    }
                    rows.push({
                        u_kh: el.kh_phid,
                        u_kh_EXName: el.kh_name,
                        u_cshte: el.init_cnt_amt_vat,
                        u_htxe: el.cnt_amt_vat,
                        u_yhkhj: el.cnt_in_pay_amt,
                        u_sdje: el.u_jstzje,
                        u_ykpsq: el['0.17'],
                        u_ykpsl: el['0.16'],
                        u_ykpss: el['0.13'],
                        u_ykpj: el['0.09'],
                        u_ykpl: el['0.06'],
                        u_ykpli: el['0'],
                        u_ykphj: (Number(el['0.17']) || 0)
                            + (Number(el['0.16']) || 0)
                            + (Number(el['0.13']) || 0)
                            + (Number(el['0.09']) || 0)
                            + (Number(el['0.06']) || 0)
                            + (Number(el['0']) || 0),
                        u_yqrsrsq: by['0.17'],
                        u_yqrsrsl: by['0.16'],
                        u_yqrsrss: by['0.13'],
                        u_yqrsrj: by['0.09'],
                        u_yqrsrl: by['0.06'],
                        u_yqrsrli: by['0']
                    })
                }
                grid5.clearRows().then(() => {
                    grid5.addRows([...rows])
                })
            })


        })
    }
});




function getQSInfo(pc) {
    const grid = $NG.getCmpApi("p_form_pc_liquid_d");
    grid.clearRows();
    $NG.execServer('GetJSInfo', { pc: pc }, function (res) {
        const data = JSON.parse(res.data);
        var gridArr = []; // 定义表体数组
        var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
                u_pc_no: '',
                amt: '',
                u_sscb: '',
                u_fsscb: '',
                u_qzbg: '',
                u_yrzcb: '',
            };
            gridObj.u_pc_no = data[i].extendObjects.bh;
            gridObj.amt = data[i].extendObjects.cspsje;
            gridObj.u_sscb = data[i].extendObjects.ssyy;
            gridObj.u_fsscb = data[i].extendObjects.fssyy;
            gridObj.u_qzbg = data[i].extendObjects.bgje;
            gridObj.u_yrzcb = data[i].extendObjects.rzcb;

            gridArr.push(gridObj);
        }

        // 清空表格内容（放在循环外部）
        grid.clearRows();

        // 调用新增表体行数据的函数
        grid.addRows(gridArr);

        // 更新RichHelp字段（如果需要）
        // 这里假设有一个方法可以刷新或重新渲染表格，以确保RichHelp字段正确显示
        grid.refreshView(); // 或者使用grid.refreshData();
    });



}

function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
        console.log(res, "count");
        switch (res.count) {
            case 0:
                return;
            case 1:
                const datas = JSON.parse(res.data)[0].extendObjects;
                const temp_map = {};
                temp_map[key] = datas.phid;
                temp_map[`${key}_EXName`] = datas.bill_name;
                $NG.updateState((updater) => {
                    updater.data[table].setProps({
                        ...temp_map,
                    });
                    setTimeout(() => {
                        if (fun) {
                            fun();
                        }
                    }, 200);
                });
        }
    });
}